const Koa = require('koa')
const { bodyParser } = require("@koa/bodyparser");
const Router = require('@koa/router');
const userRouter = require('./routes/user')
const articleRouter = require('./routes/article')
const attractionRouter = require('./routes/attraction')
const orderRouter = require('./routes/order')
const travelRouter = require('./routes/travel')
const mount = require('koa-mount');
const serve = require('koa-static')//静态资源
const cors = require('@koa/cors');//跨域
const multer = require('@koa/multer')//导入路由包
const path = require('path')//导入路由包

const {sequelize} = require('./database/index')

const app = new Koa();

(async function () {
    sequelize.sync({force:false,alter:true})//启动一次后改为false
})()

app.use(cors({
    origin(ctx) {
        return '*';
    }
}));

const storage = multer.diskStorage({
    //设置文件存储位置
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, '/upload/images'))
    },
    filename(req, file, cb) {
        // 设置 文件名
        const name = file.originalname;
        // 设置文件的后缀名，
        //我这里取的是上传文件的originalname属性的后四位，
        // 即： .png，.jpg等，这样就需要上传文件的后缀名为3位
        const extension = name.substring(name.length - 4);
        cb(null, "img-" + Date.now() + extension);
    },
})
const upload = multer({ storage: storage })

//全局挂载upload中间件
app.use(upload.array('imgfile', 5));

app.use(mount('/img', serve(__dirname + '/upload/images')));
const router = new Router(); //总路由
app.use(bodyParser());

router.use('/user', userRouter.routes(), userRouter.allowedMethods())

router.use('/article', articleRouter.routes(), articleRouter.allowedMethods())

router.use('/order', orderRouter.routes(), orderRouter.allowedMethods())

router.use('/attraction', attractionRouter.routes(), attractionRouter.allowedMethods())

router.use('/travel', travelRouter.routes(), travelRouter.allowedMethods())

app
    .use(router.routes())
    .use(router.allowedMethods());

app.listen(3000)